package com.shujia.custom.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class MyUDTFDemo1 extends GenericUDTF {

    /**
     *  规定输出的每一行列的名字以及列的数据类型
     *  学号，姓名，身份证号
     *
     */
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建一个集合存储列的名字
        ArrayList<String> nameList = new ArrayList<>();
        //创建一个集合存储列的数据类型
        ArrayList<ObjectInspector> inspectorArrayList = new ArrayList<>();

        //向列名集合中添加字段名。向类型集合添加列数据类型
        nameList.add("id");
        inspectorArrayList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        nameList.add("name");
        inspectorArrayList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        nameList.add("idcard");
        inspectorArrayList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        //将列名和字段类型匹配上
        return ObjectInspectorFactory.getStandardStructObjectInspector(nameList,inspectorArrayList);

    }

    /**
     *  处理UDTF逻辑真正代码的地方
     *  M1001#xiaohu#S324231212,lkd#M1002#S2543412432,S21312312412#M1003#bfy
     *
     * 参数可以是一列数据，也可以是很多列数据
     *
     * select xxxfun1(col1,col2,col3,col4,col5,..);
     */
    @Override
    public void process(Object[] args) throws HiveException {
        //将传进的数据转换成java的数据类型
        String info = args[0].toString();
        String[] pInfos = info.split(",");
        for (String pInfo : pInfos) {
            //遍历每个用户
            String[] infos = new String[3];
            //M1001#xiaohu#S324231212
            String[] info2 = pInfo.split("#");
            for (String info3 : info2) {
                //遍历每个用户的信息
                if(info3.startsWith("M")){
                    infos[0] = info3.substring(1);
                }else if(info3.startsWith("S")){
                    infos[2] = info3.substring(1);
                }else {
                    infos[1] = info3;
                }
            }
            //调用forward方法，将数组写出去，写出一行
            forward(infos);
        }

    }

    @Override
    public void close() throws HiveException {

    }
}
